﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace WFL.Drawing
{
    public class AnimateImage
    {
        private const int FRAMEDELAY = 0x5100;
        private const int LOOPCOUNT = 0x5101;

        private int[] _delays;

        public Image Image { get; private set; }

        public int FrameCount
        {
            get { return _delays.Length; }
        }

        public short LoopCount
        {
            get;
            private set;
        }

        public AnimateImage(Image image)
        {
            if (image == null)
            {
                throw new ArgumentNullException("image");
            }
            Image = image;
            foreach (PropertyItem propItem in Image.PropertyItems)
            {
                int len = propItem.Len;
                byte[] value = propItem.Value;
                switch (propItem.Id)
                {
                    default:
                        break;
                    case FRAMEDELAY:
                        _delays = new int[len / 4];
                        for (int i = 0; i < _delays.Length; i++)
                        {
                            _delays[i] = BitConverter.ToInt32(value, i * 4);
                        }
                        break;
                    case LOOPCOUNT:
                        LoopCount = BitConverter.ToInt16(value, 0);
                        break;
                }
            }
        }

        public int GetFrameDelay(int index)
        {
            ValidIndex(index);

            return _delays[index] * 10;
        }

        public void SelectActiveFrame(int index)
        {
            ValidIndex(index);

            FrameDimension dimension = new FrameDimension(Image.FrameDimensionsList[0]);
            Image.SelectActiveFrame(dimension, index);
        }

        private void ValidIndex(int index)
        {
            int frameCount = FrameCount;
            if (frameCount == 0)
            {
                throw new InvalidOperationException("当前图像不支持动画。");
            }
            else
            {
                if (index < 0 || index >= frameCount)
                {
                    throw new ArgumentOutOfRangeException("index小于0或超出了允许的最大值。");
                }
            }
        }
    }
}
